/**
 * @file   ReceivedPUTFILEAuthMsg.java
 * @date   2012-12-14下午4:52:00
 * @author user
 */
package com.gzceb.zhgjj.mina.PUTFILE;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gzceb.zhgjj.model.MsgFactory;
import com.gzceb.zhgjj.model.PUTFILEAuthMsg;
import com.gzceb.zhgjj.util.PropertiesUtils;

/**
 * <p>PUTFILE接口报文收发类。</p>
 *
 * @date   2012-12-14下午4:52:00 
 * @author liqing
 * @description 接收并响应6152端口的PUTFILE报文，返回给中心响应文件名
 */
public class ReceivedPUTFILEAuthMsg extends IoHandlerAdapter {

	private  final Logger logger = LoggerFactory.getLogger(getClass());
	
	public void sessionCreated(IoSession session) throws Exception {
		super.sessionCreated(session);
	    session.getConfig().setWriteTimeout(PropertiesUtils.getIntValue("msgTimeOut"));
	    session.getConfig().setReaderIdleTime(PropertiesUtils.getIntValue("msgTimeOut"));  //设置空闲时间10分钟，超时10分钟后关闭session
	       
	   }

	/**
     * 新连接打开的时候触发，在sessionCreated之后被调用
     */
	   public void sessionOpened(IoSession session) throws Exception {
		   super.sessionOpened(session);
	   }

	   public void sessionClosed(IoSession session) throws Exception {
		   super.sessionClosed(session);
	   }

	   public void sessionIdle(IoSession session, IdleStatus status)
	           throws Exception {
		   logger.debug("关闭闲置session，ip：" + session.getRemoteAddress().toString());
	       session.close(false);
	   }

	   public void exceptionCaught(IoSession session, Throwable cause)
	           throws Exception {
		   logger.error("关闭异常session。IP: " + session.getRemoteAddress() + "\n" + cause.getMessage());
	    	session.close(true);
	   }

	   /**
	     * 有消息接收的时候触发
	     * 关键步骤。
	     */
	   public void messageReceived(IoSession session, Object message)
	           throws Exception {
		   String s = ((String)message).substring(4);
		   String sndMsg;
		   PUTFILEAuthMsg pfAuthMsg = new PUTFILEAuthMsg(PropertiesUtils.getValue("destPath_PFAuth"));
		   sndMsg = pfAuthMsg.ProcRcvMsg(s);
		   session.write(sndMsg);
	   }

	   public void messageSent(IoSession session, Object message) throws Exception {
		   super.messageSent(session, message);
	   }

}
